<template>
  <el-dialog
    class="dialog"
    :title="form.id ?'编辑部门':'新增部门'"
    :visible="showDialog"
    @update:visible="closeDialog"
  >
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
      <!-- 部门名称 start-->
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model.trim="form.name"
          placeholder="请输入部门名称"
          clearable
        ></el-input>
      </el-form-item>
      <!-- 部门名称 end-->

      <!-- 部门编码 start-->
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model.trim="form.code"
          placeholder="请输入部门编码"
          clearable
        ></el-input>
      </el-form-item>
      <!-- 部门编码 end-->

      <!-- 部门负责人 start-->
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          placeholder="请选择或输入查询部门负责人"
          clearable
          filterable
          :filter-method="handleFilterManager"
          :style="{ width: '100%' }"
        >
          <!-- 负责人下拉，要调用接口，获取数据过来，再给managerOptions -->
          <el-option
            v-for="item in managerList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 部门负责人 end-->

      <!-- 部门介绍 start-->
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model.trim="form.introduce"
          type="textarea"
          placeholder="请输入部门介绍"
          :autosize="{ minRows: 4, maxRows: 4 }"
        ></el-input>
      </el-form-item>
      <!-- 部门介绍 end-->
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="cancelFn">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import msgTip  from "@/utils/message-tip";
export default {
  props: {
    //员工信息（用于选择部门负责人）
    managerOptions: {
      type: Array,
      default: () => [],
    },
    showDialog: {
      type: Boolean,
      required: true,
    },
   
    //部门信息-（用于新增、更新部门规则校验）
    departmentData: {
      type: Array,
      default: () => [],
      required: true,
    },
    //当前操作部门信息
    node: {
      type: Object,
      default: () => ({}),
      required: true,
    },
  },
  data() {
    //部门名称校验
    const validateName =  (rule, value, callback) => {
      
      let brothers;
      if (this.form.id) {
        // 编辑
        brothers = this.departmentData.filter(
          (t) => t.pid === this.node.pid && t.id !== this.node.id
        );
      } else {
        const parent = this.node;
        brothers = this.departmentData.filter((t) => t.pid === parent.id); // 解决bug：添加部门时，名称没有校验重复
      }
      const f = brothers ? brothers.find((t) => t.name === value) : false;
      f ? callback(new Error("存在重复的名称")) : callback();
    }
    // 部门编码校验
    const validateCode = (rule, value, callback) => {
    
      let f
      if (this.form.id) {
        // 编辑，排查当前部门，允许自己修改自己
        f = this.departmentData.filter(t => t.id !== this.form.id).find(t => t.code === value)
      } else {
        // 新增
        f = this.departmentData.find(t => t.code === value)
      }
      f ? callback(new Error('部门编码重复')) : callback()
    }

    return {
      managerList: [],
      form: {
        name: null, //部门名称
        code: null, //部门编码
        manager: null, //部门管理
        introduce: null, //部门简介
      },
      formRules: {
        //  部门名称（name）：必填 1-50个字符  / 同级部门中禁止出现重复部门
        name: [
          {
            required: true,
            message: "请输入部门名称",
            trigger: "blur",
          },
          {
            min: 1,
            max: 50,
            message: "长度在 1- 50 个字符",
            trigger: "blur",
          },
          {
            validator: validateName,
            trigger: "blur",
          },
        ],
        // 部门编码（code）：必填 1-50个字符  / 部门编码在整个模块中都不允许重复
        code: [
          {
            required: true,
            message: "请输入部门编码",
            trigger: "blur",
          },
          {
            min: 1,
            max: 50,
            message: "长度在 1- 50 个字符",
            trigger: "blur",
          },
          {
            validator: validateCode,
            trigger: "blur",
          },
        ],
        // 部门负责人（manager）：必填
        manager: [
          {
            required: true,
            message: "请选择部门负责人",
            trigger: "change",
          },
        ],
        // 部门介绍 ( introduce)：必填 1-300个字符
        introduce: [
          {
            required: true,
            message: "请输入部门介绍",
            trigger: "blur",
          },
          {
            min: 1,
            max: 300,
            message: "长度在 1- 300 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    managerOptions: {
      handler() {
        this.managerList = this.managerOptions.slice(1, 30);
      },
      immediate: true, // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法
    },
  },

  methods: {
    handleFilterManager(value) {
      //数据量过多搜索解决
      const list = this.managerOptions.filter((item) => {
        return item.username && item.username.includes(value);
      });

      // 根据检索条件筛选出来的选项，只取前30条
      if (list.length > 30) {
        this.managerList = list.slice(0, 30);
      } else {
        this.managerList.splice(0, list.length, ...list);
      }
    },
    //btn-取消
    cancelFn() {
      this.closeDialog(); //关闭弹窗
    },
    //确认提交
    confirm() {
      this.$refs.formRef.validate(valid=>{
        if(valid){
          this.$emit("confirm", { ...this.form });
        }else{
          msgTip({msg:'请正确填写表单',type:'warning'})
        }

      })
      
    },
    //关闭弹窗 表单重置
    closeDialog() {
      this.$emit("update:showDialog", false);
      this.form = this.$options.data().form; //表单重置
    },
  },
};
</script>
